package com.ithzl.capacity.controller;

import com.ithzl.capacity.pojo.RESTful.RestBean;
import com.ithzl.capacity.pojo.User;
import com.ithzl.capacity.service.LoginService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @PostMapping
    public RestBean login(HttpSession session,@Param("number") String number,@Param("password") String password){

        // 查询是否有
        User user=loginService.login(number,password);

        // 有返回成功
        // 没有返回失败
        if(user!=null){
            session.setAttribute("user",user);
            session.setMaxInactiveInterval(60*60*2);
            return RestBean.succeed(user,"登录成功");
        }
        else {
            return RestBean.fail("登录失败");
        }
    }

    @GetMapping("/logout")
    public RestBean logout(HttpSession session){
        User user= (User) session.getAttribute("user");
        if (user!=null){
            session.removeAttribute("user");
            return RestBean.succeed();
        }
        else {
            return RestBean.fail("无登录用户");
        }
    }
}
